var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var queryurl = config.BASEPATH+'money/streamsettle/temp_list';
var _height = $(parent).height()-325,_width = $(parent).width()-2;

var Utils = {
	doQueryBank : function(){
		commonDia = $.dialog({
			title : '选择银行账户',
			content : 'url:'+config.BASEPATH+'money/bank/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#st_ba_code").val(selected.ba_code);
				$("#ba_name").val(selected.ba_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#st_ba_code").val(selected.ba_code);
					$("#ba_name").val(selected.ba_name);
				}
			},
			cancel:true
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#st_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	temp_entire:function(){
		var discount_money = $("#discount_money").val();//优惠金额
    	var paid = $("#paid").val();//实付金额
    	discount_money = discount_money == "" || isNaN(discount_money) ? 0.0 : parseFloat(discount_money);
    	paid = paid == "" || isNaN(paid) ? 0.0 : parseFloat(paid);
    	
    	if(parseFloat($("#realdebt").val()) > 0 && paid < 0){
    		Public.tips({type: 2, content : '请输入正数！'});
			$("#paid").val("0.00").select();
    		return;
    	}
    	if(discount_money == 0 && paid == 0){
    		Public.tips({type: 2, content : '请输入自动分配相关金额！'});
			$("#paid").focus();
			return;
    	}
    	if(discount_money > totalPositive){
			Public.tips({type: 2, content : '优惠金额不能大于应付金额！'});
			$("#discount_money").val("0.00").select();
			return;
		}
		if (paid < totalNegative) {
    		$("#paid").val("0.00").select();
    		Public.tips({type: 2, content : '实付金额过小！'});
    		return;
    	}
		$.dialog.confirm('确定要自动分配吗?',function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'money/streamsettle/temp_entire',
				data:{discount_money:discount_money,paid:paid},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : '自动分配成功！'});
						THISPAGE.reloadGridData();
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		},
		function(){
		});
	},
	temp_updateRemark:function(rowid,remark){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'money/streamsettle/temp_updateRemark',
			data:{stl_id:rowid,stl_remark:Public.encodeURI(remark)},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
    temp_updateDiscountMoney:function(rowid,money,realMoney){
    	var params = {stl_id:rowid,stl_discount_money:money};
    	if(realMoney != undefined && realMoney != null){
    		params.stl_real_pay = realMoney;
    	}
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'money/streamsettle/temp_updateDiscountMoney',
			data:params,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
    temp_updateRealMoney:function(rowid,money){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'money/streamsettle/temp_updateRealMoney',
			data:{stl_id:rowid,stl_real_pay:money},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
	save:function(){
		if (!$("#form1").valid()) {
			return;
		}
		var rowIds = $("#grid").jqGrid('getDataIDs');
		if (rowIds.length == 0){
			Public.tips({type: 2, content : '没有单据进行支付！'});
			return;
		}
		var sum = 0.0;
    	var st_discount_money = $("#st_discount_money").val();
    	var st_paid = $("#st_paid").val();
    	sum += parseFloat(st_discount_money)+parseFloat(st_paid);
    	if(sum == 0){
    		Public.tips({type: 2, content : '结算金额为0，无法保存!'});
            return;
    	}
    	var tip = "";
    	tip += $("#stream_name").val()+"：<br/>";
    	tip += "应付账款："+$("#realdebt").val()+"元。<br/>";
    	tip += "本次结算："+sum.toFixed(2)+"元，其中优惠金额："+st_discount_money+"元，实付金额："+st_paid+"元。"
    	tip+="<br/><b>你确定要结算单据吗?</b>";
    	$.dialog.confirm(tip,
            function () {
	    		$("#btn-save").attr("disabled",true);
	    		var saveUrl = config.BASEPATH+"money/streamsettle/save";
	    		if($("#st_id").val() != undefined){
	    			saveUrl = config.BASEPATH+"money/streamsettle/update";
	    		}
	    		$.ajax({
	    			type:"POST",
	    			url:saveUrl,
	    			data:$('#form1').serialize(),
	    			cache:false,
	    			dataType:"json",
	    			success:function(data){
	    				if(undefined != data && data.stat == 200){
	    					Public.tips({type: 3, content : '保存成功'});
	    					handle.loadData(data.data);
	    				}else{
	    					Public.tips({type: 1, content : data.message});
	    				}
	    				$("#btn-save").attr("disabled",false);
	    			}
	    		});
            },
            function () {
                return;
            }
        );
	},
	loadData:function(data){
		var pdata = {};
		pdata.id=data.st_id;
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	formatState:function(val, opt, row){
		var sum = parseFloat(row.stl_discount_money) + parseFloat(row.stl_real_pay);
    	if(Math.abs(sum) >= Math.abs(parseFloat(row.stl_unpayable)) || parseFloat(sum).toFixed(2) == parseFloat(row.stl_unpayable).toFixed(2)){
        	return '已付清';
        }else{
        	return '未付清';
        }
	},
	formatColor:function(rowid){
    	var rowData = $("#grid").jqGrid("getRowData", rowid);
		if(rowData.state == '已付清'){
        	$("#grid").jqGrid('setRowData', rowid, null,{ color: '#696969' });
        }else if(rowData.state == '未付清'){
        	$("#grid").jqGrid('setRowData', rowid, null,{ color : 'red'});
        }
    },
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-plus" title="新增">&#xe639;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '</div>';
		return html_con;
	}
};

var totalNegative = 0.0;
var totalPositive = 0.0;

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();
	},
	initDom:function(){
		$("#st_date").val(config.TODAY);
		this.selectRow={};
		if($("#st_id").val() == undefined){
			this.temp_save();
		}
	},
	temp_save:function(){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'money/streamsettle/temp_save',
			data:{"se_code":$("#st_stream_code").val()},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					THISPAGE.reloadGridData();
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	gridTotal:function(){
    	var grid=$('#grid');
		var stl_payable=grid.getCol('stl_payable',false,'sum');
		var stl_payabled=grid.getCol('stl_payabled',false,'sum');
		var stl_discount_money_yet=grid.getCol('stl_discount_money_yet',false,'sum');
		var stl_unpayable=grid.getCol('stl_unpayable',false,'sum');
		var stl_discount_money=grid.getCol('stl_discount_money',false,'sum');
		var stl_real_pay=grid.getCol('stl_real_pay',false,'sum');
    	grid.footerData('set',{stl_bill_number:'合计：',
    		stl_payable:stl_payable,
    		stl_payabled:stl_payabled,
    		stl_discount_money_yet:stl_discount_money_yet,
    		stl_unpayable:stl_unpayable,
    		stl_discount_money:stl_discount_money,
    		stl_real_pay:stl_real_pay
    	});
    },
    calcParentMoney:function(){
    	var st_discount_money = 0.0;
        var st_paid = 0.0;
        var rowIds = $("#grid").jqGrid('getDataIDs');
        var rowData = null;
        for (var i = 0; i < rowIds.length; i++) {
            rowData = $("#grid").jqGrid("getRowData", rowIds[i]);
            st_discount_money = st_discount_money + parseFloat(rowData.stl_discount_money);
            st_paid = st_paid + parseFloat(rowData.stl_real_pay);
        }
        $("#st_discount_money").val(st_discount_money.toFixed(2));
        $("#st_paid").val(st_paid.toFixed(2));
        
        $("#discount_money").val(st_discount_money.toFixed(2));
        var realdebt = parseFloat($("#realdebt").val());//实际欠款
        var leftdebt = realdebt - st_discount_money - st_paid;
        $("#leftdebt").val(leftdebt.toFixed(2));
    },
	initGrid:function(){
		var self=this;
		var colModel = [
	    	{label:'单据编号',name: 'stl_bill_number',index: 'stl_bill_number',width:150},
	    	{label:'应付总金额',name: 'stl_payable', index: 'stl_payable', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney},
	    	{label:'已付金额',name: 'stl_payabled', index: 'stl_payabled', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney},
	    	{label:'已优惠金额',name: 'stl_discount_money_yet', index: 'stl_discount_money_yet', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney},
	    	{label:'未付金额',name: 'stl_unpayable', index: 'stl_unpayable', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney},
	    	{label:'优惠金额',name: 'stl_discount_money', index: 'stl_discount_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney,editable:true},
	    	{label:'实付金额',name: 'stl_real_pay', index: 'stl_real_pay', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney,editable:true},
	    	{label:'状态',name: 'state', index: 'state', width: 100,formatter: handle.formatState},
	    	{label:'备注',name: 'stl_remark', index: 'stl_remark', width: 180,editable:true}
	    ];
		var datatype = 'local';
		if($("#st_id").val() != undefined){
			datatype = 'json';
		}
		$('#grid').jqGrid({
			url:queryurl,
			loadonce:true,
			datatype: datatype,
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:false,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
			cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'stl_id'  //图标ID
			},
			loadComplete: function(data){
				var ids = $("#grid").jqGrid('getDataIDs');
				totalNegative = 0.0;
            	totalPositive = 0.0;
				for (var i = 0; i < ids.length; i++) {
					var rowData = $("#grid").jqGrid("getRowData", ids[i]);
					if(rowData.state == '已付清'){
                    	$("#grid").jqGrid('setRowData', ids[i], null,{ color: '#696969' });
                    }else if(rowData.state == '未付清'){
                    	$("#grid").jqGrid('setRowData', ids[i], null,{ color : 'red'});
                    }
					if(parseFloat(rowData.stl_unpayable)<0){
                    	totalNegative +=parseFloat(rowData.stl_unpayable);
                    }else{
                    	totalPositive +=parseFloat(rowData.stl_unpayable);
                    }
				}
				THISPAGE.gridTotal();
				THISPAGE.calcParentMoney();
			},
			loadError: function(xhr, status, error){		
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){
            	self.selectRow.value=value;
				return value;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				if(self.selectRow.value == value){
					return self.selectRow.value;
				}
				if(cellname == 'stl_remark'){
					handle.temp_updateRemark(rowid, value);
					return value;
				}
				if(cellname == 'stl_discount_money' || cellname == 'stl_real_pay'){
					if(value == '' || isNaN(value)){
						return self.selectRow.value;
					}
					if(parseFloat(self.selectRow.value) == parseFloat(value)){
						return parseFloat(value).toFixed(2);
					}
					
					var stl_real_pay = null;
            		var rowData = $("#grid").jqGrid("getRowData", rowid);
            		if(cellname == 'stl_discount_money'){
            			if(rowData.stl_unpayable < 0){
            				Public.tips({type: 2, content : '未付金额为负数，不可以修改此金额！'});
            				return self.selectRow.value;
            			}
            			if(parseFloat(value) < 0){
            				Public.tips({type: 2, content : '优惠金额不能输入负数！'});
                			return self.selectRow.value;
            			}
            			
            			if(Math.abs(parseFloat(value)) > Math.abs(parseFloat(rowData.stl_unpayable))){
            				Public.tips({type: 2, content : '优惠金额不能大于应付金额！'});
                			return self.selectRow.value;
            			}
    					stl_real_pay = parseFloat(rowData.stl_unpayable) - parseFloat(value);
    					handle.temp_updateDiscountMoney(rowid, parseFloat(value).toFixed(2), stl_real_pay);
						$("#grid").jqGrid('setRowData', rowid, {stl_real_pay:stl_real_pay});
    					return parseFloat(value).toFixed(2);
            		}
            		if(cellname == 'stl_real_pay'){
            			var tempSum = 0;
            			tempSum += parseFloat(value);
            			tempSum += parseFloat(rowData.stl_discount_money);
            			if(tempSum > rowData.stl_unpayable || tempSum < 0){
            				Public.tips({type: 2, content : '实付金额超出范围！'});
    						return self.selectRow.value;
            			}
            			handle.temp_updateRealMoney(rowid, parseFloat(value).toFixed(2));
                		return parseFloat(value).toFixed(2);
            		}
				}
				return value;
			},
			afterSaveCell:function(rowid, cellname, value, iRow, iCol){
				if(self.selectRow.value == value){
					return;
				}
				if(cellname == 'stl_discount_money' || cellname == 'stl_real_pay'){
					var rowData = $("#grid").jqGrid("getRowData", rowid);
					rowData.state = '';
					$("#grid").jqGrid('setRowData', rowid, rowData);
        			handle.formatColor(rowid);
        			THISPAGE.gridTotal();
    				THISPAGE.calcParentMoney();
				}
			}
	    });
	},
	reloadGridData: function () {
        $("#grid").jqGrid('setGridParam', {datatype: 'json', page: 1, url: queryurl}).trigger("reloadGrid");
    },
	initEvent:function(){
		$('#btn-save').on('click', function(e){
			e.preventDefault();
			handle.save();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
        $('#AutoMatch').click(function(e){
        	e.preventDefault();
        	handle.temp_entire();
        });
        $('#discount_money').on('keyup',function(e){
    		if (e.keyCode==13){
    			$("#paid").select();
    		}
    	});
        $('#paid').on('keyup',function(e){
    		if (e.keyCode==13){
    			$('#AutoMatch').click();
    		}
    	});
        $('#discount_money').on('blur',function(){
        	if(parseFloat(this.value) == 0){
        		return;
        	}
        	if(parseFloat(this.value) > totalPositive){
    			Public.tips({type: 2, content : '优惠金额不能大于未付金额！'});
    			$('#discount_money').val('0.00').select();
    		}
    	});
	}
};

THISPAGE.init();